package cn.org.authority.service;

import cn.org.authority.bean.MyUser;
import cn.org.authority.bean.Permission;
import cn.org.authority.bean.Role;
import cn.org.authority.dao.PermissionMapper;
import cn.org.authority.dao.RoleMapper;
import cn.org.authority.dao.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 登陆的权限认证逻辑
 * @ClassName MyUserService
 * @Author swj
 * @Date 2020/9/9 20:10
 */
@Component
public class MyUserDetailService implements UserDetailsService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        logger.info("登陆用户名:{}",s);
        MyUser user = userMapper.getUserByName(s);
        if (user == null) {
            logger.error("不存在用户");
            return null;
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>(8);
        List<Role> roles = roleMapper.getRolebyUser(user.getId());
        logger.info(roles.toString());

        for (Role role : roles) {
            List<Permission> permissions = permissionMapper.getPermissionsByRole(role.getId());
            for (Permission permission : permissions) {
                List<String> permissionDos = permissionMapper.getDoByPermission(permission.getId());
                for (String permissionDo : permissionDos) {
                    authorities.add(new SimpleGrantedAuthority(String.format("%s-%s", permission.getId(),permissionDo)));
                }
            }
        }
        logger.info(authorities.toString());
        logger.info("登陆用户的密码{}",user.getPassword());

        return new User(s,user.getPassword(), true, true, true, true,
                authorities);
    }
}
